package cn.momoky.ccool.advice;

import cn.momoky.ccool.exception.GlobalException;
import cn.momoky.ccool.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@AllArgsConstructor
@RestControllerAdvice(basePackages = "cn.momoky.ccool.controller")
public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {

    ObjectMapper om;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        try {
            if (o instanceof String) {
                return om.writeValueAsString(Result.ok(o));
            } else if (o instanceof Result ) {
                return o;
            } else {
                return Result.ok(o);
            }
        } catch (JsonProcessingException e) {
            log.error("JsonProcessingException!Reason:{}",e.getMessage());
        }
        return null;
    }

    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandle(HttpServletRequest request, Exception e) {
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            log.error("GlobalException!Reason:{}",ex.getMessage());
            return Result.error(ex.getCode(), ex.getMessage());
        } else {
            log.error("Exception:{}",e.getMessage());
            return Result.error();
        }
    }
}
